package com.hunk.core.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @see Http代理访问本地fusioncharts等功能应用
 * @see
 * @author Hunk
 * @since 2013-3-20
 */
public class HttpProxy extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String LOCALHOST = "http://127.0.0.1:8898/fxb/fxbCharts.jsp?";
	/** 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("deprecation")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		StringBuffer query = new StringBuffer(LOCALHOST);

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();		
		query.append(request.getQueryString());		
		
		try {
			query.replace(0, query.length(), URLDecoder.decode(query.toString()));
		} catch (Exception exception) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST,
					"URL decode error " + exception);
			return;
		}
		BufferedReader in = null;
		try {
			URL url = new URL(query.toString());
			in = new BufferedReader(new InputStreamReader(
					url.openStream()));

			String line;
			while ((line = in.readLine()) != null)
				out.println(line);
			out.flush();
		} catch (IOException exception) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND, "Exception: "
					+ exception);
		} finally {
			try {
			if (in != null) in.close(); 
			} catch (Exception ex) {
				System.out.println("url close err!");
			}
		}
	}
}
